package safeCommitter.core.view.action.relaunch;

import java.util.Collections;
import java.util.Set;

import org.eclipse.core.runtime.CoreException;
import org.eclipse.jface.action.Action;

import safeCommitter.core.launcher.ISCLauncher;
import safeCommitter.core.launcher.socket.SCSocketReader;
import safeCommitter.core.launcher.socket.SCVMSocketLauncher;
import safeCommitter.core.listener.SCListener;
import safeCommitter.core.template.Activator;
import safeCommitter.core.view.main.SCReportContentProvider;
import safeCommitter.test.executor.launcher.internal.SCTestArgsBuilder;
import safeCommitter.test.executor.launcher.socket.SCTestSocketReader;
import safeCommitter.test.report.ISCTestResult;

public abstract class RelaunchAction extends Action {

	protected static final String MAIN_CLASS = "safeCommitter.test.executor.SCTestExecutor";

	protected final SCReportContentProvider reportProvider;

	public RelaunchAction(SCReportContentProvider reportProvider) {
		this.reportProvider = reportProvider;
		buildMenu();
	}

	@Override
	public void run() {
		ISCTestResult selectedTest = reportProvider.getSelectedTest();
		if (selectedTest == null) {
			return;
		}
		try {
			execute(Collections.singleton(selectedTest));
		} catch (CoreException e) {
			e.printStackTrace();
		}
	}

	private void execute(Set<ISCTestResult> testsToRelaunch)
			throws CoreException {
		SCSocketReader reader = new SCTestSocketReader();
		ISCLauncher launcher = new SCVMSocketLauncher(Activator.getDefault()
				.getJavaProject(), reader);
		String filePath = SCTestArgsBuilder
				.getTestExecutorArgs(testsToRelaunch);
		launcher.runClazz(isDebug(), true, MAIN_CLASS, new SCListener(),
				filePath);
	}

	protected abstract void buildMenu();

	protected abstract Boolean isDebug();

}
